package com.myjava.managesystem.filter;


import com.alibaba.fastjson.JSON;
import com.myjava.managesystem.common.BaseContext;
import com.myjava.managesystem.common.R;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;

@Slf4j
@WebFilter(filterName = "logincheckfilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    public static String[] urls ={
            "/employee/login",
            "/employee/logout",
            "/backend/**",
            "/front/**",
            "/common/**",
            "/user/login",
            "/user/sendMsg/**",
    };


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = request.getRequestURI();
        if(!checkUrl(url)){
            if(request.getSession().getAttribute("employee")!=null){
                BaseContext.setCurrentId((Long) request.getSession().getAttribute("employee"));
                filterChain.doFilter(request,response);
                return;
            }
            if(request.getSession().getAttribute("user")!=null){
                BaseContext.setCurrentId((Long) request.getSession().getAttribute("user"));
                filterChain.doFilter(request,response);
                return;
            }
            log.info("拦截到未登录用户"+url);
            response.getWriter().write(JSON.toJSONString(R.error("NOT LOGIN")));
        }
        else{
            filterChain.doFilter(request,response);
        }

    }


    public static boolean checkUrl(String url){
        for(String s:urls){
            boolean match = PATH_MATCHER.match(s, url);
            if(match){
                return match;
            }
        }
        return false;
    }
}
